﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web.Configuration;

namespace Macds.Core.IoC
{
    public class ObjectsConfigurationGroup : ConfigurationSectionGroup
    {
        public static ObjectsConfigurationGroup Load()
        {
            System.Configuration.Configuration config = null;

            try
            {
                config = WebConfigurationManager.OpenWebConfiguration("~");
            }
            catch
            {
                config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            }

            return (ObjectsConfigurationGroup)config.GetSectionGroup("IoCs");
        }

        public ObjectElement GetObject(string name)
        {
            ObjectElement element = null;

            for (int i = 0; i < this.Sections.Count; i++)
            {
                var section = (ObjectsConfigurationSection)this.Sections[i];
                if (section.Objects.Contains(name))
                {
                    element = section.Objects[name];
                    break;
                }
            }

            if (element == null)
                throw new NullReferenceException(String.Format("The object {0} does not exist in the configuration file", name));

            return element;
        }

        public ClassElement GetClassType(string name)
        {
            ClassElement element = null;

            for (int i = 0; i < this.Sections.Count; i++)
            {
                var section = (ObjectsConfigurationSection)this.Sections[i];
                if (section.Types.Contains(name))
                {
                    element = section.Types[name];
                    break;
                }
            }

            if (element == null)
                throw new NullReferenceException("The object does not exist in the configuration file");

            return element;
        }
    }
}
